package org.example.struct.array;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liyishan
 * @date 2024/9/19 10:41
 * @apiNote
 */

public class Test03090MaximumLengthSubstring {
    public int maximumLengthSubstring(String s) {
        int n = s.length();
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;
        int r = -1;
        for(int i =0;i<n;i++){
            if(i != 0){
                map.put(s.charAt(i-1),map.getOrDefault(s.charAt(i-1),0)-1);
                if(map.get(s.charAt(i-1)) == 0){
                    map.remove(s.charAt(i-1));
                }
            }
            while(r < n-1 && map.getOrDefault(s.charAt(r+1),0) < 2){
                map.put(s.charAt(r+1),map.getOrDefault(s.charAt(r+1),0)+1);
                r++;
            }

            max = Math.max(max,r+1-i);
        }
        return max;
    }

    public int maximumLengthSubstring1(String s) {
        char[] chars = s.toCharArray();
        int ans = 0;
        int left = 0;
        int[] cnt = new int[26];
        for(int i =0;i<s.length();i++){
            int b = chars[i] - 'a';
            cnt[b]++;
            while(cnt[b] > 2){
                cnt[chars[left++]-'a']--;
            }
            ans = Math.max(ans,i-left+1);
        }
        return ans;
    }
}
